<template>
  <div class="chat-container">
    <!-- 侧边栏 - 聊天列表 -->
    <el-aside width="240px" class="chat-sidebar">
      <div class="sidebar-header">
        <el-button type="primary" icon="Plus" size="small" class="new-chat-btn" @click="createNewChat">
          新建对话
        </el-button>
      </div>
      <el-scrollbar class="chat-list-scroll">
        <div class="chat-list">
          <div class="chat-item active" v-for="chat in chatSessions" :key="chat.id" @click="switchChat(chat.id)">
            <div class="chat-info">
              <div class="chat-title">{{ chat.title }}</div>
              <div class="chat-preview">{{ chat.lastMessage }}</div>
            </div>
            <div class="chat-actions">
              <el-icon class="delete-icon" @click.stop="deleteChat(chat.id)"><Delete /></el-icon>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-aside>

    <!-- 主聊天区域 -->
    <el-main class="chat-main">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="current-chat-title">{{ currentChat.title || '新对话' }}</div>
        <div class="chat-toolbar">
          <el-icon class="toolbar-icon"><Refresh /></el-icon>
          <el-icon class="toolbar-icon"><Download /></el-icon>
          <el-icon class="toolbar-icon"><More /></el-icon>
        </div>
      </div>

      <!-- 聊天消息区域 -->
      <el-scrollbar class="chat-messages">
        <div class="message-list">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="welcome-icon"></div>
            <p>开始与AI助手对话吧！</p>
            <p>我可以帮你解答问题、创作内容、提供建议...</p>
          </div>

          <!-- 消息气泡 -->
          <div v-for="(msg, index) in messages" :key="index" class="message-item">
            <div :class="['message-bubble', msg.isUser ? 'user-message' : 'ai-message']">
              <div class="message-avatar">
                <img :src="msg.isUser ? userAvatar : aiAvatar" alt="头像">
              </div>
              <div class="message-content">
                <div class="message-text">{{ msg.content }}</div>
                <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
              </div>
            </div>
          </div>

          <!-- 加载中状态 -->
          <div v-if="isLoading" class="loading-message">
            <el-avatar class="loading-avatar">
              <img src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" alt="AI头像">
            </el-avatar>
            <div class="loading-content">
              <div class="dot-pulse"></div>
            </div>
          </div>
        </div>
      </el-scrollbar>

      <!-- 输入区域 -->
      <div class="chat-input-area">
        <div class="input-toolbar">
          <el-icon class="toolbar-btn"><Image /></el-icon>
          <el-icon class="toolbar-btn"><Smile /></el-icon>
          <el-icon class="toolbar-btn"><Paperclip /></el-icon>
        </div>
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="4"
          placeholder="输入消息..."
          class="message-input"
          @keyup.enter.exact="sendMessage"
        ></el-input>
        <div class="send-btn-container">
          <el-button type="primary" @click="sendMessage" :disabled="!inputMessage.trim()">
            发送
          </el-button>
        </div>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElScrollbar } from 'element-plus'
import { Plus, Delete, Refresh, Download, More, Smile, Paperclip } from '@element-plus/icons-vue'

// 路由和导航
const route = useRoute()
const router = useRouter()

// 模拟数据 - 聊天会话
const chatSessions = ref([
  { id: '1', title: 'AI创作', lastMessage: '帮我写一首关于春天的诗', timestamp: Date.now() - 3600000 },
  { id: '2', title: '数学问题', lastMessage: '如何解一元二次方程？', timestamp: Date.now() - 1800000 },
  { id: '3', title: '代码优化', lastMessage: '帮我看看这段JavaScript代码', timestamp: Date.now() - 600000 }
])

// 当前聊天会话
const currentChat = ref({
  id: route.params.id || 'new',
  title: '',
  messages: []
})

// 消息列表
const messages = ref([])
// 输入框内容
const inputMessage = ref('')
// 加载状态
const isLoading = ref(false)
// 头像
const userAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
const aiAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 切换聊天会话
const switchChat = (chatId) => {
  // 在实际应用中，这里应该从API加载对应会话的消息
  const chat = chatSessions.value.find(c => c.id === chatId)
  if (chat) {
    currentChat.value = { ...chat, messages: [] }
    // 模拟加载消息
    messages.value = [
      { isUser: true, content: chat.lastMessage, timestamp: Date.now() - 3000 },
      { isUser: false, content: '这是一条模拟的AI回复，在实际应用中会调用DeepSeekR1接口获取真实响应。', timestamp: Date.now() - 2000 }
    ]
  }
}

// 创建新对话
const createNewChat = () => {
  const newChatId = Date.now().toString(36)
  router.push({ name: 'Chat', params: { id: newChatId }})
  currentChat.value = { id: newChatId, title: '新对话', messages: [] }
  messages.value = []
}

// 删除对话
const deleteChat = (chatId) => {
  chatSessions.value = chatSessions.value.filter(chat => chat.id !== chatId)
  // 如果删除的是当前对话，跳转到首页
  if (currentChat.value.id === chatId) {
    router.push('/')
  }
  ElMessage.success('对话已删除')
}

// 发送消息
const sendMessage = () => {
  const content = inputMessage.value.trim()
  if (!content) return

  // 添加用户消息
  const userMessage = {
    isUser: true,
    content,
    timestamp: Date.now()
  }
  messages.value.push(userMessage)
  inputMessage.value = ''

  // 如果是新对话，设置标题
  if (!currentChat.value.title) {
    currentChat.value.title = content.length > 20 ? content.substring(0, 20) + '...' : content
    chatSessions.value.unshift({
      id: currentChat.value.id,
      title: currentChat.value.title,
      lastMessage: content,
      timestamp: Date.now()
    })
  }

  // 模拟AI响应
  isLoading.value = true
  setTimeout(() => {
    const aiResponse = {
      isUser: false,
      content: '这是DeepSeekR1接口返回的模拟响应。在实际应用中，这里会通过Axios调用后端API，再由后端转发请求到DeepSeekR1接口获取真实响应。\n\n响应内容可以包含多行文本、代码块或其他格式化内容。',
      timestamp: Date.now()
    }
    messages.value.push(aiResponse)
    isLoading.value = false

    // 更新最后一条消息
    const index = chatSessions.value.findIndex(chat => chat.id === currentChat.value.id)
    if (index !== -1) {
      chatSessions.value[index].lastMessage = aiResponse.content.length > 20 ? aiResponse.content.substring(0, 20) + '...' : aiResponse.content
      chatSessions.value[index].timestamp = Date.now()
    }
  }, 1500)
}

// 页面加载时初始化
onMounted(() => {
  // 如果是新对话，初始化
  if (route.params.id && route.params.id !== 'new') {
    const existingChat = chatSessions.value.find(c => c.id === route.params.id)
    if (existingChat) {
      switchChat(route.params.id)
    } else {
      // 新创建的对话
      currentChat.value.id = route.params.id
      currentChat.value.title = '新对话'
      messages.value = []
    }
  }
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.chat-sidebar {
  background-color: #fff;
  border-right: 1px solid #e5e9f2;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #e5e9f2;
}

.new-chat-btn {
  width: 100%;
}

.chat-list-scroll {
  flex: 1;
  height: 0;
}

.chat-list {
  padding: 10px;
}

.chat-item {
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 5px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: #f5f7fa;
}

.chat-item.active {
  background-color: #e6f7ff;
}

.chat-info {
  flex: 1;
  overflow: hidden;
}

.chat-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-preview {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-icon {
  color: #f5222d;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
}

.chat-item:hover .delete-icon {
  opacity: 1;
}

.chat-main {
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: #f9fafc;
}

.chat-header {
  height: 60px;
  border-bottom: 1px solid #e5e9f2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
}

.current-chat-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.chat-toolbar {
  display: flex;
  gap: 15px;
}

.toolbar-icon {
  color: #666;
  cursor: pointer;
  transition: color 0.2s;
}

.toolbar-icon:hover {
  color: #039be5;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  height: 0;
}

.message-list {
  max-width: 800px;
  margin: 0 auto;
}

.welcome-message {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.welcome-icon {
  width: 80px;
  height: 80px;
  background-color: #e6f7ff;
  border-radius: 50%;
  margin: 0 auto 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.welcome-icon::after {
  content: 'AI';
  color: #039be5;
  font-size: 32px;
  font-weight: bold;
}

.message-item {
  margin-bottom: 20px;
}

.message-bubble {
  display: flex;
  max-width: 70%;
}

.user-message {
  flex-direction: row-reverse;
  margin-left: auto;
}

.ai-message {
  margin-right: auto;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  margin: 0 10px;
  max-width: calc(100% - 60px);
}

.user-message .message-content {
  background-color: #039be5;
  color: #fff;
  border-top-right-radius: 4px;
}

.ai-message .message-content {
  background-color: #fff;
  color: #333;
  border: 1px solid #e5e9f2;
  border-top-left-radius: 4px;
}

.message-text {
  line-height: 1.5;
  font-size: 14px;
  margin-bottom: 5px;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  text-align: right;
}

.loading-message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.loading-avatar {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.loading-content {
  background-color: #fff;
  border: 1px solid #e5e9f2;
  border-radius: 18px;
  border-top-left-radius: 4px;
  padding: 15px;
}

.dot-pulse {
  display: flex;
  gap: 4px;
}

.dot-pulse::before, .dot-pulse::after, .dot-pulse span {
  content: '';
  width: 8px;
  height: 8px;
  background-color: #039be5;
  border-radius: 50%;
  animation: dotPulse 1.4s infinite ease-in-out both;
}

.dot-pulse::before { animation-delay: -0.32s; }
.dot-pulse span { animation-delay: -0.16s; }

@keyframes dotPulse {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.chat-input-area {
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #e5e9f2;
}

.input-toolbar {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  color: #666;
}

.toolbar-btn {
  cursor: pointer;
  transition: color 0.2s;
}

.toolbar-btn:hover {
  color: #039be5;
}

.message-input {
  border-radius: 8px;
  resize: none;
}

.send-btn-container {
  text-align: right;
  margin-top: 10px;
}
</style>